package com.sxkiler.demo.netty.protocol;


import com.sxkiler.demo.netty.handler.Invocation;
import com.sxkiler.demo.netty.register.RemoteRegisterFactory;
import com.sxkiler.demo.netty.register.RegisterType;
import com.sxkiler.demo.netty.register.RemoteRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.URL;

public class ProxyFactory {

    public static <T> T getProxy(final ProtoclType protoclType , final RegisterType registerType, final Class interfaceClass){
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Protocl protocl = ProtoclFactory.getProtocl(protoclType);
                Invocation invocation = new Invocation(interfaceClass.getName(),method.getName(),method.getParameterTypes(),args);
                RemoteRegister remoteRegister = RemoteRegisterFactory.getRemoteRegister(registerType);
                URL radomURL = remoteRegister.getRadomURL(interfaceClass.getName());
                System.out.println("调用地址host:"+ radomURL.getHost()+ ",port:"+radomURL.getPort());
                return protocl.invokeProtocl(radomURL,invocation);
            }
        });
    }
}